<template>
  <div class="camera-container">
    <!-- 左侧表单 -->
    <div class="camera-form">
      <h2 class="form-title">Camera Tools</h2>

      <!-- 路径选择 -->
      <el-form label-width="80px">
        <el-form-item label="Path">
          <el-select
            v-model="selectedPathId"
            placeholder="Select camera path"
            style="width: 100%"
            @change="handlePathChange"
          >
            <el-option
              v-for="path in pathList"
              :key="path.id"
              :label="path.name"
              :value="path.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 选中路径的详情 -->
      <div v-if="selectedPath" class="path-details">
        <div class="path-header">
          <el-divider>Path Settings</el-divider>
          <el-checkbox v-model="selectedPath.isClosed">Closed Path</el-checkbox>
        </div>

        <!-- Key Points 列表 -->
        <div class="key-points">
          <div class="points-header">
            <h3>Key Points</h3>
            <el-button type="primary" link @click="handleAddPoint">
              <el-icon><Plus /></el-icon>
              Add Point
            </el-button>
          </div>

          <div v-for="(point, index) in selectedPath.views" :key="index" class="point-item">
            <div class="point-header">
              <span class="point-title">Point {{ index + 1 }}</span>
              <el-button type="danger" link @click="handleRemovePoint(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>

            <!-- Position -->
            <div class="coordinate-group">
              <div class="group-label">Position</div>
              <div class="coordinate-item">
                <span class="coordinate-label">X:</span>
                <el-input-number
                  v-model="point.position.x"
                  :step="1"
                  :precision="2"
                  controls-position="right"
                />
              </div>
              <div class="coordinate-item">
                <span class="coordinate-label">Y:</span>
                <el-input-number
                  v-model="point.position.y"
                  :step="1"
                  :precision="2"
                  controls-position="right"
                />
              </div>
              <div class="coordinate-item">
                <span class="coordinate-label">Z:</span>
                <el-input-number
                  v-model="point.position.z"
                  :step="1"
                  :precision="2"
                  controls-position="right"
                />
              </div>
            </div>

            <!-- Rotation -->
            <div class="coordinate-group">
              <div class="group-label">Rotation</div>
              <div class="coordinate-item">
                <span class="coordinate-label">Yaw:</span>
                <el-input-number
                  v-model="point.rotation.yaw"
                  :min="0"
                  :max="360"
                  :step="1"
                  :precision="2"
                  controls-position="right"
                />
              </div>
              <div class="coordinate-item">
                <span class="coordinate-label">Pitch:</span>
                <el-input-number
                  v-model="point.rotation.pitch"
                  :min="0"
                  :max="360"
                  :step="1"
                  :precision="2"
                  controls-position="right"
                />
              </div>
              <div class="coordinate-item">
                <span class="coordinate-label">Roll:</span>
                <el-input-number
                  v-model="point.rotation.roll"
                  :min="0"
                  :max="360"
                  :step="1"
                  :precision="2"
                  controls-position="right"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 保存按钮 -->
        <div class="path-actions">
          <el-button type="primary" @click="handleSavePath">Save Path</el-button>
          <el-button type="danger" @click="handleDeletePath">Delete Path</el-button>
        </div>
      </div>

      <!-- 创建新路径 -->
      <div class="create-path">
        <el-divider>Create New Path</el-divider>
        <el-form :model="newPathForm" label-width="80px">
          <el-form-item label="Name">
            <el-input v-model="newPathForm.name" placeholder="Enter path name" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleCreatePath">Create</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 右侧画布 -->
    <div class="camera-canvas" :style="backgroundStyle" ref="canvasContainer">
      <canvas ref="canvas"></canvas>
      <!-- 点位图标容器 -->
      <div class="points-container">
        <template v-if="selectedPath">
          <!-- 连接线 -->
          <svg class="path-lines">
            <path
              :d="getPathLines"
              stroke="#409EFF"
              stroke-width="2"
              fill="none"
              stroke-dasharray="5,5"
            />
          </svg>

          <!-- 点位图标 -->
          <div
            v-for="(point, index) in selectedPath.views"
            :key="index"
            class="point-icon"
            :style="{
              left: `${point.position.x * 100}%`,
              top: `${point.position.y * 100}%`,
              transform: `translate(-50%, -50%) rotate(${point.rotation.yaw}deg)`
            }"
            @click="handlePointClick(index)"
          >
            <div class="icon-wrapper">
              <el-icon
                :size="20"
                :color="currentPointIndex === index ? '#67C23A' : '#409EFF'"
              >
                <VideoCamera />
              </el-icon>
            </div>
            <div class="point-label">{{ index + 1 }}</div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed, onBeforeUnmount} from 'vue'
import { Plus, Delete, VideoCamera } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {cameraList, cameraUpdate, cameraDelete, getMap, pointAdd, cameraCreate} from '../api'

const canvas = ref(null)
const canvasContainer = ref(null)
const backgroundStyle = ref({})
const pathList = ref([])
const selectedPathId = ref(null)
const selectedPath = ref(null)

// 新建路径表单
const newPathForm = reactive({
  name: ''
})

// 当前选中的点位索引
const currentPointIndex = ref(null)

// 获取背景图片
function getBackgroundImage() {
  getMap().then(res => {
    if (res.success) {
      backgroundStyle.value = {
        backgroundImage: `url(${res.image})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }
    }
  })
}

// 处理路径选择
function handlePathChange(pathId) {
  const path = pathList.value.find(p => p.id === pathId)
  selectedPath.value = JSON.parse(JSON.stringify(path)) // 深拷贝
}

// 添加关键点
function handleAddPoint() {
  pointAdd({

  }).then(res => {
    if (res.success) {
      selectedPath.value.views.push(res.data)
    }
  })
}

// 移除关键点
function handleRemovePoint(index) {
  selectedPath.value.views.splice(index, 1)
}

// 保存路径
function handleSavePath() {
  cameraUpdate(selectedPath.value).then(res => {
    if (res.success) {
      ElMessage.success('Path saved successfully')
    }
  })
}

// 创建新路径
function handleCreatePath() {
  if (!newPathForm.name) {
    ElMessage.warning('Please enter path name')
    return
  }
  // if (!selectedPath.value) {
  //   ElMessage.warning('Please select path')
  //   return
  // }
  // let data = selectedPath.value
  // data.name = newPathForm.name
  // delete(data.id)
  let data = {
    "name": newPathForm.name,
    "isClosed": false,
    "views": []
  }
  cameraCreate(data).then(res => {
    if (res.success) {
      ElMessage.success('Path created successfully')
      // 重置表单
      newPathForm.name = ''
      // 刷新列表并自动选中新创建的路径
      getCameraList().then(() => {
        // 根据名称找到新创建的路径（假设返回的数据中有ID或可以通过名称匹配）
        const newPath = pathList.value.find(p => p.name === data.name)
        if (newPath) {
          selectedPathId.value = newPath.id
          handlePathChange(newPath.id)
        }
      })
    }
  })
}

// 删除路径
function handleDeletePath() {
  ElMessageBox.confirm('Are you sure to delete this path?', 'Warning', {
    confirmButtonText: 'Confirm',
    cancelButtonText: 'Cancel',
    type: 'warning',
  }).then(() => {
    cameraDelete({
      id: selectedPath.value.id
    }).then(res => {
      if (res.success) {
        ElMessage.success('Path deleted successfully')
        // 重置选中状态
        selectedPath.value = null
        selectedPathId.value = null
        // 重新获取路径列表
        getCameraList()
      }
    })
  })
}

function getCameraList() {
  return cameraList().then(res => {
    if (res.success) {
      pathList.value = res.data
    }
  })
}

// 处理点击点位
function handlePointClick(index) {
  currentPointIndex.value = index
  // 可以在这里添加其他交互逻辑
}

// 计算路径连接线
const getPathLines = computed(() => {
  if (!selectedPath.value.views.length) return ''

  // 获取容器尺寸，用于计算绝对坐标
  const container = canvasContainer.value
  if (!container) return ''
  const width = container.clientWidth
  const height = container.clientHeight

  const points = selectedPath.value.views.map(point => ({
    // 将百分比转换为绝对坐标
    x: (point.position.x * width),
    y: (point.position.y * height)
  }))

  // 如果只有一个点，不绘制线
  if (points.length < 2) return ''

  let path = `M ${points[0].x} ${points[0].y}`

  // 连接所有点
  for (let i = 1; i < points.length; i++) {
    path += ` L ${points[i].x} ${points[i].y}`
  }

  // 如果是闭合路径且点数大于2，连接首尾
  if (selectedPath.value.isClosed && points.length > 2) {
    path += ` L ${points[0].x} ${points[0].y}`
  }

  return path
})

// 监听窗口大小变化，重新计算路径
window.addEventListener('resize', () => {
  if (selectedPath.value) {
    // 触发路径重新计算
    selectedPath.value = { ...selectedPath.value }
  }
  resizePreview()
})

onMounted(() => {
  resizePreview()
  getBackgroundImage()
  getCameraList()
})

function resizePreview() {
  if (canvasContainer.value) {
    canvasContainer.value.style.width = canvasContainer.value.offsetHeight + 'px'
  }
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizePreview)
})
</script>

<style scoped>
.camera-container {
  display: flex;
  height: 100%;
  gap: 20px;
  overflow: hidden;
}

.camera-form {
  width: 600px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  overflow-y: auto;
  overflow-x: hidden;
}

.camera-canvas {
  height: 100%;
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  position: relative;
}

.form-title {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  border-bottom: 1px solid #EBEEF5;
}

.path-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.points-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.points-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.point-item {
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.point-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.point-title {
  font-weight: bold;
  color: #303133;
}

.coordinate-group {
  margin-bottom: 16px;
}

.group-label {
  font-weight: bold;
  color: #606266;
  margin-bottom: 8px;
}

.coordinate-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.coordinate-label {
  width: 45px;
  text-align: right;
  color: #606266;
  font-size: 14px;
}

.path-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;  /* 添加按钮之间的间距 */
  margin-top: 20px;
}

.create-path {
  margin-top: 40px;
}

:deep(.el-input-number) {
  flex: 1;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-right: 0;
}

.points-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.point-icon {
  position: absolute;
  cursor: pointer;
  pointer-events: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  z-index: 1; /* 确保点位图标在线上方 */
}

.icon-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.point-icon:hover .icon-wrapper {
  transform: scale(1.2);
}

.point-label {
  font-size: 12px;
  color: #fff;
  background: #409EFF;
  padding: 2px 6px;
  border-radius: 10px;
  pointer-events: none;
}

.path-lines {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
}
</style>
